<?php
require_once 'service.php';
require_once 'model/UserManager.php';
require_once 'exceptions/AuthenticationException.php';
require_once 'util/constants.php';

class LoginService extends Service {
	
	/* models */
	private $oUserManager;	// connection to user table	
	
    public function LoginService() {    	
        $this->oUserManager = new UserManager();
        
        parent::__construct('html/login.html', false);
    }
    
	/**
	 * Authenticate user by username and password and then start a session
	 */
	public function login() {
        try {
            $this->startSession($this->oUserManager->authenticateUser($this->asParams["username"],
                                                                      $this->asParams["password"]));
            $this->success();
        } catch(Exception $e) {
            $this->error($e->getMessage());
        }
	}
    
    /**
     * Logout the user and echo the reason
     */
    public function logout() {    	
    	if($this->getSessionStatus() == SESSIONACTIVE) {
	    	// destroy cookies
		    if (ini_get("session.use_cookies")) {
			    $acCookieParams = session_get_cookie_params();
			    setcookie(session_name(), '', time() - 42000, $acCookieParams["path"],
			        $acCookieParams["domain"], $acCookieParams["secure"], $acCookieParams["httponly"]
			    );
			}
	    	
	        $_SESSION = array();	// empty $_SESSION        
	        session_destroy();
    	}
        $this->showPage();
    }
	
	/**
	 * start session
	 * @param unknown_type $$oUser->_id
	 */
	private function startSession($oUser) {
		if(!isset($_SESSION['userID']) ||
		   !isset($_SESSION['hash'])) {
            session_start();
			$_SESSION['userID'] = $oUser->userID;
			$_SESSION['hash'] = $oUser->hash;
		}
        return $this->getSessionStatus();
	}
}

$loginService = new LoginService();
?>
